//
//  RegisterViewController.m
//  EasyToTesco
//
//  Created by mc on 16/2/26.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "RegisterViewController.h"
#import "HeaderFileForEasyToTesco.h"

#import "AFNetworking.h"

#import "MineViewController.h"
#import "MainTabBarController.h"

#define registerMarc 30
#define labelWeith 70

@interface RegisterViewController ()<UITextFieldDelegate, UIAlertViewDelegate>{
    UIImageView *seletImage;
}

@property(nonatomic, strong)UITextField *phoneNumber;
@property(nonatomic, strong)UITextField *UserName;
//密码和确认密码
@property(nonatomic, strong)UITextField *passWordOne;
@property (nonatomic, strong)UITextField *passWordTwo;

//二级密码


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addRegisterTopViewUI];
    
    [self addRegisterUI];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotfication) name:MainLoginPostNotificationName object:nil];
}

//- (void)receiveNotfication
//{
//    NSLog(@"11111111111");
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

- (void)addRegisterTopViewUI {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"注册";

}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
//    MainTabBarController *main = [[MainTabBarController alloc] init];
//    main.selectedViewController =
//    self.view.window.rootViewController =
}

- (void)addRegisterUI {
    UIImageView *iconPic = [[UIImageView alloc] initWithFrame:CGRectMake((WEITH-100)/2, HIGHT*0.1+30, 100, 100)];
//    iconPic.backgroundColor = [UICo
    
    iconPic.image = [UIImage imageNamed:@"icon_login"];
    [self.view addSubview:iconPic];
    
    
    UILabel *phoneNumlabel = [[UILabel alloc] initWithFrame:CGRectMake(registerMarc, CGRectGetMaxY(iconPic.frame)+30, labelWeith, 30)];
    phoneNumlabel.text = @"用户名:";
    phoneNumlabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:phoneNumlabel];
    
    UITextField *phoneNumber = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(phoneNumlabel.frame), CGRectGetMaxY(iconPic.frame)+30, WEITH-registerMarc*2-CGRectGetWidth(phoneNumlabel.frame), 30)];
    phoneNumber.layer.borderWidth = 1;
    phoneNumber.layer.borderColor = [UIColor blackColor].CGColor;
    phoneNumber.layer.cornerRadius = 6;
    phoneNumber.layer.masksToBounds = YES;
    phoneNumber.delegate = self;
    phoneNumber.placeholder = @"请输入手机号码";
    phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
    phoneNumber.clearButtonMode = UITextFieldViewModeAlways;
    phoneNumber.font = [UIFont systemFontOfSize:14];
    self.phoneNumber = phoneNumber;
    [self.view addSubview:self.phoneNumber];
    

    UILabel *usernamelabel = [[UILabel alloc] initWithFrame:CGRectMake(registerMarc, CGRectGetMaxY(phoneNumber.frame)+10, labelWeith, 30)];
    usernamelabel.text = @"设置密码:";
    usernamelabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:usernamelabel];
    
    UITextField *userName = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(phoneNumlabel.frame), CGRectGetMaxY(phoneNumber.frame)+10, WEITH-registerMarc*2-CGRectGetWidth(phoneNumlabel.frame), 30)];
    userName.layer.borderWidth = 1;
    userName.layer.borderColor = [UIColor blackColor].CGColor;
    userName.layer.cornerRadius = 6;
    userName.layer.masksToBounds = YES;
    userName.delegate = self;
    userName.placeholder = @"请输入6-20位,数字或字母组成";
    userName.secureTextEntry = YES;
    userName.clearButtonMode = UITextFieldViewModeAlways;
    userName.font = [UIFont systemFontOfSize:14];
    self.UserName = userName;
    [self.view addSubview:self.UserName];
    
    
    UILabel *passwordOneLabel = [[UILabel alloc] initWithFrame:CGRectMake(registerMarc, CGRectGetMaxY(userName.frame)+10, labelWeith, 30)];
    passwordOneLabel.text = @"确认密码:";
    passwordOneLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:passwordOneLabel];
    
    UITextField *passWordOne = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(passwordOneLabel.frame), CGRectGetMaxY(usernamelabel.frame)+10, WEITH-registerMarc*2-CGRectGetWidth(passwordOneLabel.frame), 30)];
    passWordOne.layer.borderWidth = 1;
    passWordOne.layer.borderColor = [UIColor blackColor].CGColor;
    passWordOne.layer.cornerRadius = 6;
    passWordOne.layer.masksToBounds = YES;
    passWordOne.delegate = self;
    passWordOne.placeholder = @"再次输入,并保证两次输入一致";
    passWordOne.secureTextEntry = YES;
    passWordOne.clearButtonMode = UITextFieldViewModeAlways;
    passWordOne.font = [UIFont systemFontOfSize:14];
    self.passWordOne = passWordOne;
    [self.view addSubview:self.passWordOne];
    
    UILabel *passwordTwoLabel = [[UILabel alloc] initWithFrame:CGRectMake(registerMarc, CGRectGetMaxY(passwordOneLabel.frame)+10, labelWeith, 30)];
    passwordTwoLabel.text = @"二级密码:";
    passwordTwoLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:passwordTwoLabel];
    
    UITextField *passWordTwo = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(passwordTwoLabel.frame), CGRectGetMaxY(passwordOneLabel.frame)+10, WEITH-registerMarc*2-CGRectGetWidth(passwordTwoLabel.frame), 30)];
    passWordTwo.layer.borderWidth = 1;
    passWordTwo.layer.borderColor = [UIColor blackColor].CGColor;
    passWordTwo.layer.cornerRadius = 6;
    passWordTwo.layer.masksToBounds = YES;
    passWordTwo.delegate = self;
    passWordTwo.placeholder = @"请输入二级密码";
    passWordTwo.secureTextEntry = YES;
    passWordTwo.clearButtonMode = UITextFieldViewModeAlways;
    passWordTwo.font = [UIFont systemFontOfSize:14];
    self.passWordTwo = passWordTwo;
    [self.view addSubview:self.passWordTwo];
    
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.frame = CGRectMake(registerMarc, CGRectGetMaxY(passWordTwo.frame)+50, WEITH-registerMarc*2, 40);
    registerBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    registerBtn.layer.cornerRadius = 6;
    registerBtn.layer.masksToBounds = YES;
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    
    seletImage = [[UIImageView alloc] initWithFrame:CGRectMake(registerMarc, CGRectGetMaxY(registerBtn.frame)+10, 20, 20)];
    seletImage.layer.borderWidth = 1;
    [self.view addSubview:seletImage];
    
    UIButton *buttonOne = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonOne.frame = seletImage.frame;
    buttonOne.tag = 1001;
    [buttonOne setBackgroundImage:[UIImage imageNamed:@"duigou"] forState:UIControlStateNormal];
    buttonOne.layer.borderWidth = 1;
//    [buttonOne setBackgroundColor:[UIColor ;
#warning didClick
    
    [buttonOne addTarget:self action:@selector(OtherBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonOne];
    
    UILabel *onelabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(seletImage.frame)+5, CGRectGetMaxY(registerBtn.frame)+10, 70, 20)];
    onelabel.font= [UIFont systemFontOfSize:10];
    onelabel.text = @"我已阅读并同意";
    [self.view addSubview:onelabel];
    
    UILabel *twolabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(onelabel.frame), CGRectGetMaxY(registerBtn.frame)+10, 80, 20)];
    twolabel.font= [UIFont systemFontOfSize:10];
    twolabel.text = @"《用户服务协议》";
    twolabel.textColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [self.view addSubview:twolabel];
    
    UIButton *buttonTwo = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonTwo.frame = twolabel.frame;
    buttonTwo.tag = 1002;
    [buttonTwo addTarget:self action:@selector(OtherBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonTwo];
    
    UILabel *threeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(twolabel.frame), CGRectGetMaxY(registerBtn.frame)+10, 80, 20)];
    threeLabel.text = @"服务条款";
    threeLabel.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:threeLabel];
    
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(WEITH-registerMarc-100, CGRectGetMaxY(threeLabel.frame), 100, 30);
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loginBtn setTitle:@"已有账户,现在登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(gobackRegisiterVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    
    
}


- (void)OtherBtnClick:(UIButton *)button{
    
//    if (button.selected) {
//        [button setBackgroundImage:[UIImage imageNamed:@"duigou.jpg"] forState:UIControlStateSelected];
//        button.layer.borderWidth = 1;
//    } else {
//        button.layer.borderWidth = 1;
//    }
    
    NSLog(@"%ld", button.tag);
}


- (void)registerBtnClick{
    NSLog(@"注册按钮");
    if (self.UserName.text.length != 0 && self.phoneNumber.text.length != 0 && self.passWordOne.text.length != 0 && self.passWordTwo.text.length != 0) {
        BOOL judge = [self isMobileNumber:self.phoneNumber.text];
        if (judge == YES) {
            if (![self.UserName.text isEqualToString:self.passWordOne.text]) {
                UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"两次输入密码不一致.请重新输入!\n" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alview show];
                self.UserName.text = nil;
                self.passWordOne.text = nil;
                [self.UserName resignFirstResponder];
            } else {
                 [self requestregisterDatasourse];
            }
        } else {
            UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式有误, 请重新输入..." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
        }
        
    } else {
        UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"请完善您的注册信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }
    

}


//判断手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188, 183
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186 145
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189  181
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


- (void)gobackRegisiterVC {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- UITextFieldDelegate
//触摸空白处回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//    [self.PhoneNumTextField resignFirstResponder];
    
    [self.phoneNumber resignFirstResponder];
    [self.UserName resignFirstResponder];
    [self.passWordOne resignFirstResponder];
    [self.passWordTwo resignFirstResponder];

}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.phoneNumber) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength >= 12) {
            return NO;
        }
    }
   
    
    return YES;
}

//实时监控键盘的状态
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.phoneNumber) {
        if (textField.text.length >=12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
    
#pragma mark -- 在这里判断手机号码的归属地
//    if ([textField.text isEqualToString:@"123456"]) {
//        self.NumberInfo.text = @"归属地改变了";
//    }
    NSLog(@"当前----===:%@", textField.text);
}

#pragma mark --- 注册页面数据加载
- (void)requestregisterDatasourse {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
   
    
    NSString *username = self.phoneNumber.text;
    NSString *password = self.passWordOne.text;
    NSString *userpwtwo = self.passWordTwo.text;
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username], @"password":[NSString stringWithFormat:@"%@", password], @"userpwtwo":[NSString stringWithFormat:@"%@", userpwtwo]};
    
    __weak RegisterViewController *registerSelf = self;
    
    [mgr POST:@"http://www.ylgw8.com/AppUser/Reg" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        
        
        NSDictionary *dic = [registerSelf toArrayOrNSDictionary:responseObject];
        
        if ([[NSString stringWithFormat:@"%@", dic[@"code"]] isEqual:@"1"]) {
            UIAlertView *LoginAlview1 = [[UIAlertView alloc] initWithTitle:@"注册成功" message:@"恭喜您,注册成功, 返回登录" delegate:registerSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            LoginAlview1.tag = 120;
            [LoginAlview1 show];
        } else {
            
                UIAlertView *LoginAlview = [[UIAlertView alloc] initWithTitle:@"注册失败" message: [NSString stringWithFormat:@"%@", dic[@"message"]] delegate:registerSelf cancelButtonTitle:@"返回登录" otherButtonTitles:@"重新注册", nil];
                LoginAlview.tag = 121;
                [LoginAlview show];
            
        }
        NSLog(@"%@", string);
        
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
                  NSLog(@"数据请求错误原因:%@", error);
                  NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}
// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

#pragma mark -- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 120) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else  {
        if (buttonIndex == 0) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }else {
            self.phoneNumber.text = nil;
            self.UserName.text = nil;
            self.passWordOne.text = nil;
            self.passWordTwo.text = nil;
            [self.phoneNumber resignFirstResponder];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
